package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.SearchSimpleActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.dialog.JobknowledgeDragDialog;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.CustomerViewpager;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/7/12.
 */

public class JobknowledgeFragment extends Fragment implements View.OnClickListener, ResultSubscriber.OnResultListener {

	private static final int GET_TAB_DATA_CODE = 0x01;
	private static final int SET_SKILL_LEVEL_CODE = 0x02;
	private static final int TAB_SORT_CODE = 0x03;

	protected Context mContext;
	protected View contentView;
	@ViewInject(R.id.module_name)
	protected TextView titleName;
	@ViewInject(R.id.icon_serach)
	protected ImageView searchBtn;
	@ViewInject(R.id.tab_view)
	private TabView tabView;
	@ViewInject(R.id.sort_btn)
	private ImageView sortBtn;
	@ViewInject(R.id.view_page)
	private CustomerViewpager viewPager;

	private List<PositionKnowlegeMode> tabDatas;
	private List<JobKnowledgeDataFragment> fragments;
	private FragmentStatePagerAdapter pagerAdapter;

	private String cachePath;
	private FileCacheManager cacheManager;

	private JobknowledgeDragDialog dragDialog;
	private LocalBroadCast localBroadCast;
	private LocalBroadcastManager localBroadcastManager;

	public void showDragDialog(){
		if(contentView != null)
			onClick(sortBtn);
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if(contentView == null) {
			mContext = getContext();
			contentView = inflater.inflate(R.layout.fragment_base_tab, container, false);
			x.view().inject(this, contentView);
			init();
		}
		return contentView;
	}

	@Override
	public void onDestroy() {
		localBroadcastManager.unregisterReceiver(localBroadCast);
		saveTabDatas();
		super.onDestroy();
	}

	@Override
	public void onResume() {
		super.onResume();
		tabView.setTabSelectIndex(viewPager.getCurrentItem());
	}

	protected void init(){
		titleName.setText("岗位知识");
		searchBtn.setOnClickListener(this);
		sortBtn.setOnClickListener(this);
		searchBtn.setVisibility(View.GONE);

		tabDatas = new ArrayList<>();
		fragments = new ArrayList<>();

		pagerAdapter = new FragmentStatePagerAdapter(getFragmentManager()) {
			@Override
			public Fragment getItem(int position) {
				return fragments.get(position);
			}
			@Override
			public int getCount() {
				return fragments.size();
			}
			@Override
			public int getItemPosition(Object object) {
				return POSITION_NONE;
			}
		};
		viewPager.setAdapter(pagerAdapter);
		tabView.setupWithViewPager(viewPager);

		cachePath = mContext.getCacheDir() + "/skillCache_position_knowlege_all.dat";
		cacheManager = new FileCacheManager();

		initDialog();
		initBroadcase();
		reacTabDatas();
	}

	private void initDialog(){
		dragDialog = new JobknowledgeDragDialog(mContext);
		dragDialog.setItemDragListener(new JobknowledgeDragDialog.ItemDragListener() {
			int positon;
			@Override
			public void onMove(int fromPosition, int toPosition) {
				PositionKnowlegeMode moveModel = tabDatas.remove(fromPosition);
				tabDatas.add(toPosition, moveModel);
				positon = toPosition;
			}
			@Override
			public void onDragFinish() {
				updateView(tabDatas);
				viewPager.setCurrentItem(positon, false);
			}
		});
		dragDialog.setLevelSelectedListener(new JobknowledgeDragDialog.LevelSelectedListener() {
			@Override
			public void onLevelSelected(int level) {
				JsonObject param = new JsonObject();
				param.addProperty("skillLevel", level);
//				HttpHelper.getInstance(mContext).updateUserInfo(param, level * 10 + SET_SKILL_LEVEL_CODE, JobknowledgeFragment.this);
				HttpHelper.getInstance(mContext).updateSkillLevel(param, level * 10 + SET_SKILL_LEVEL_CODE, JobknowledgeFragment.this);
			}
		});
		dragDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				JsonObject param = new JsonObject();
				List<HeadLine> headLines = new ArrayList<>();
				for(PositionKnowlegeMode model : tabDatas){
					HeadLine headLine = new HeadLine();
					headLine.setTypeId(model.getNavType());
					headLine.setTypeName(model.getName());
					headLines.add(headLine);
				}
				param.addProperty("type", 12);
				param.add("data", new Gson().toJsonTree(headLines, new TypeToken<List<HeadLine>>() {}.getType()).getAsJsonArray());
				HttpHelper.getInstance(mContext).headLineUpdate(param, TAB_SORT_CODE, JobknowledgeFragment.this);
			}
		});
	}

	private void initBroadcase(){
		localBroadCast = new LocalBroadCast(new LocalBroadCast.BroadCastCallBack() {
			@Override
			public void done(Context context, Intent intent) {
				getTabData();
			}
		});
		IntentFilter intent = new IntentFilter();
		intent.addAction(LocalBroadCast.GET_LOGIN_INFO);
		intent.addAction(LocalBroadCast.USER_DATA_CHANGE);
		intent.addAction(LocalBroadCast.LOGOUT_SUCCESS_BROD);
		intent.addAction(LocalBroadCast.PAY_TO_READ);
		localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
		localBroadcastManager.registerReceiver(localBroadCast, intent);
	}

	private void reacTabDatas(){
		Observable.create(new Observable.OnSubscribe<List<PositionKnowlegeMode>>() {
			@Override
			public void call(Subscriber<? super List<PositionKnowlegeMode>> subscriber) {
				List<PositionKnowlegeMode> datas = (List<PositionKnowlegeMode>) cacheManager.readObject(cachePath);
				subscriber.onNext(datas);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<List<PositionKnowlegeMode>>() {
			@Override
			public void onCompleted() {
				getTabData();
			}
			@Override
			public void onError(Throwable e) {
				onCompleted();
			}
			@Override
			public void onNext(List<PositionKnowlegeMode> data) {
				if(data != null && data.size() > 0)
					tabDatas.addAll(data);
				updateView(tabDatas);
			}
		});
	}

	protected void saveTabDatas(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				cacheManager.wirteObject(tabDatas, cachePath);
			}
		}).start();
	}

	@Override
	public void onClick(View v) {
		if(v == searchBtn && tabDatas.size() > viewPager.getCurrentItem()){
			SearchSimpleActivity.gotoSearch(mContext, tabDatas.get(viewPager.getCurrentItem()).getNavType(), 13, 2, 1);
		} else if(v == sortBtn){
			UserData userData = ((JpApplication)getActivity().getApplication()).getUserData();
			dragDialog.show(tabDatas, userData == null ? 1 : userData.getSkillLevel());
		}
	}

	protected void updateView(List<PositionKnowlegeMode> datas){
		List<String> tabNames = new ArrayList<>();
		if(datas == null){
			fragments.clear();
		} else {
			List<JobKnowledgeDataFragment> tmpFragments = new ArrayList<>();
			tmpFragments.addAll(fragments);
			fragments.clear();
			for(int i = 0; i < datas.size(); i++){
				PositionKnowlegeMode mode = datas.get(i);
				tabNames.add(mode.getName());
				if(i >= fragments.size())
					fragments.add(createFragment(mode));
				else
					fragments.get(i).updateView(mode);
			}
			while (fragments.size() > datas.size())
				fragments.remove(fragments.size()-1);
		}
		searchBtn.setVisibility(tabNames.size() == 0 ? View.GONE : View.VISIBLE);
		pagerAdapter.notifyDataSetChanged();
		tabView.setTabItems(tabNames);
	}

	protected JobKnowledgeDataFragment createFragment(PositionKnowlegeMode mode){
		return JobKnowledgeDataFragment.newInstance(mode);
	}

	private void getTabData(){
		HttpHelper.getInstance(mContext).getSkill(new JsonObject(), GET_TAB_DATA_CODE, this);
	}

	@Override
	public void onStart(int requestType) {}
	@Override
	public void onCompleted(int requestType) {}
	@Override
	public void onError(int requestType) {
		onCompleted(requestType);
		if(requestType == GET_TAB_DATA_CODE) {
			tabView.postDelayed(new Runnable() {
				@Override
				public void run() {
					getTabData();
				}
			}, 1000);
		}
	}
	@Override
	public void onNext(IModel data, int requestType) {
		if(data.getErrcode() != 0){
			if(requestType != GET_TAB_DATA_CODE)
				ToasUtil.toast(mContext, data.getMessage());
			onError(requestType);
		} else if(requestType == GET_TAB_DATA_CODE) {
			tabDatas.clear();
			List<PositionKnowlegeMode> datas = data.getList(PositionKnowlegeMode.class);
			if(datas != null && datas.size() > 0)
				tabDatas.addAll(datas);
			updateView(tabDatas);
		} else if(requestType == TAB_SORT_CODE){
			localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.HEAD_LINE_SORT));
		} else if(requestType%10 == SET_SKILL_LEVEL_CODE){
			int level = requestType/10;
			UserData userData = ((JpApplication)getActivity().getApplication()).getUserData();
			if(userData != null)
				userData.setSkillLevel(level);
			localBroadcastManager.sendBroadcast(new Intent(LocalBroadCast.USER_DATA_CHANGE));
		}
	}
}
